/*
 * @Author: CemCode cemoment@aliyun.com
 * @Date: 2022-01-17 14:45:48
 * @LastEditors: CemCode cemoment@aliyun.com
 * @LastEditTime: 2022-11-25 20:05:18
 * @FilePath: \nodejs-blog-admin\utils\log-tools.js
 * @Description: 
 * Copyright (c) 2022 by CemCode cemoment@aliyun.com, All Rights Reserved. 
 */
const fs = require("fs");
const _path = require("path");
const {
    format,
    json
} = require("./index");
let nowDate = format(Date.now(), 1);
let basicPath = _path.join(process.cwd(),"/log");
let nowLogFilePath = "blog_" + nowDate + "_log.log";
let path = _path.join(basicPath,nowLogFilePath);
//日志类型
const types = [
    "error",
    "warning",
    "info"
];

if (!fs.existsSync(basicPath)) {
    console.log("create mkdir:"+basicPath);
    fs.mkdirSync(basicPath);
}
if (!fs.existsSync(path)) {
    console.log("writeFile :"+path);
    fs.writeFileSync(path, `create time : ${nowLogFilePath}\n`);
}

//插入日志信息
function insertLogInfo(index, msg) {
    console.log("insertLogInfo ："+index+" "+msg);
    mkLog().then(() => {
        fs.appendFile(path, logM(msg, 0), err => {
            if (err) {
                console.log(err);
            }
        })
    })
}


//日志内容模板
function logM(info, type) {
    return `创建时间:${format(Date.now())} ${types[type]}:${info}\n`;
}


//判断是否存在该日志文件
function mkLog() {
    return new Promise((resolve, reject) => {
        const date = format(Date.now()).split(" ");
        if (nowDate != date[0]) {
            nowDate = date[0];
            nowLogFilePath = "blog_" + nowDate + "_log.log";
            path = _path.join(basicPath,nowLogFilePath);
            fs.writeFileSync(path, `create time : ${nowLogFilePath}\n`);
        }
        resolve();
    })
}


//异常中间件
function errM(err, req, res, next) {
    //捕获到异常
    insertLogInfo(0, err.stack);
    if(err.name === "UnauthorizedError") return res.send(json("身份认证失败!",1));

    switch (err.message) {
        case "Cannot read property 'body' of undefined":
            return res.send(json("未传入参数"));
        break;
        default:
            res.send(json(err));
    }
}

module.exports = {
    insertLogInfo,
    errM
}